<?php


namespace app\common\lib;


use app\common\cachemodel\NatalReport;
use app\common\cachemodel\Recode;
use app\common\lib\astrolog\NatalReport as NatalReportLib;
use app\common\model\MessageCenter;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use think\Log;
use think\queue\Job;

class NatalReportJob
{
    protected $type = [
        39 => 'feelings', // 恋爱
        40 => 'dating', // 婚姻
        41 => 'money', // 财富
        42 => 'carrer', // 事业
        52 => 'academic', // 学业
        54 => 'feelings', // 恋爱 精简版
        55 => 'dating', // 婚姻 精简版
        56 => 'money', // 财富 精简版
        57 => 'carrer', // 事业 精简版
        58 => 'academic', // 学业 精简版
    ];

    /**
     * 本命预测队列计算
     * @param Job $job
     * @param $jobData
     * @throws GuzzleException
     */
    public function task1(Job $job, $jobData): void
    {
        // 入队 1=》修改本命预测状态和content 2=》修改订单状态
//        订单编号和赠送二者留其一
//        $jobData = [
//            'uid' =>number 用户id,
//            'recode'=> array 档案信息,
//            'unlock_gids'=>[1,2,3],
//            'order_id' => string 订单编号
//            'aid'=> 赠送id
//        ];

        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
        }

        $host = Util::getEcsIp();
        $startTime = date('Y-m-d H:i:s');
        $logInfo = "本命预测计算 开始:{$startTime} host:{$host} uid:{$jobData['recode']['uid']} rid:{$jobData['recode']['id']} name:{$jobData['recode']['name']}";

        $now_time = time();
        try
        {
            if (isset($jobData['order_id']) && $jobData['order_id'])
            {
                $where = ['order_num' => $jobData['order_id']];
            } else
            {
                $where = ['give_id' => $jobData['aid']];
            }
            $NatalReport = new NatalReport();
            $OrdersModel = new \app\common\cachemodel\Orders();
            $NatalReportLib = NatalReportLib::getInstance();
            $natalData = $NatalReport->where($where)->column('gid', 'id');
            foreach ($natalData as $k => $value)
            {
                $config = ['money' => false, 'feelings' => false, 'dating' => false, 'carrer' => false, 'academic' => false];
                $config[$this->type[$value]] = true;
                $data = $NatalReportLib->setUserRecode($jobData['recode'])
                    ->setConfig(['getReports' => $config])->getReports($this->type[$value]);
                $data = $data ? json_encode($data, true) : '';
                $NatalReport->UpdateData($jobData['uid'], $jobData['recode']['id'], ['status' => 2, 'update_time' => $now_time, 'content' => $data], ['id' => $k]);
            }
            $error = $NatalReportLib->getError();
            if ($error !== '')
            {
                $logInfo .= ' error:' . $error;
            }
            if (isset($jobData['order_id']))
            {
                $OrdersModel->UpdateData($jobData['order_id'], ['status' => 4, 'update_time' => $now_time], 4);
            }
            $res = true;
            $job->delete();
        }
        catch (Exception $e)
        {
            $res = false;
            // 本命预测失败
            $logInfo .= ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine();
        }

        if ($res === true && isset($jobData['push_switch']) && $jobData['push_switch'])
        {
            $recodeStatus = (new Recode())->getInfoById($jobData['recode']['id'], ['status']);
            if ($recodeStatus['status'])
            {
                if ($jobData['unlock_gids'] && count($jobData['unlock_gids']) === 1)
                {
                    $ulock_gids = current($jobData['unlock_gids']);
                    $pushData = ['rid' => $jobData['recode']['id'], 'gid' => $ulock_gids, 'action' => 'report_details'];
                    // 消息中心跳转地址
                    $messageLink = 'report_details?rid=' . $jobData['recode']['id'] . '&gid=' . $ulock_gids . '&need_auth=1';
                } else
                {
                    $pushData = ['rid' => $jobData['recode']['id'], 'action' => 'report_index'];
                    // 消息中心跳转地址
                    $messageLink = 'report_index?rid=' . $jobData['recode']['id'] . '&need_auth=1';
                }
            } else
            {
                $messageLink = "order_details?order_id={$jobData['order_id']}&order_type=7&need_auth=2";
                $pushData = ['target' => 'local', 'link' => $messageLink, 'action' => 'extend'];
            }

            // 消息中心添加信息
            $messageData = [
                'status' => 0,
                'is_read' => 0,
                'range' => $jobData['uid'],
                'type' => 2,
                'reid' => 0,
                'cid' => 4,// 本命预测
                'title' => '一生报告计算完成',
                'content' => '您购买的' . $jobData['recode']['name'] . '的一生报告已经计算完成了，点击查看详情！',
                'link' => $messageLink,
                'target' => 'local',
                'create_time' => $now_time
            ];
            try
            {
                (new MessageCenter())->pushMessage($jobData['uid'], $messageData);
                // PUSH推送报告首页
                $pushRes = (new Push())->pushUserMsg($jobData['uid'], '您购买的' . $jobData['recode']['name'] . '的一生报告已经计算完成了，点击查看详情！', $pushData);
                if (!$pushRes['success'])
                {
                    $logInfo .= ' error: 计算完成,推送失败 message:' . $pushRes['message'];
                }
            }
            catch (Exception $e)
            {
                $logInfo .= ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine();
            }
        }
        $logInfo .= ' jobData:' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        print(date('Y-m-d H:i:s') . ' ' . $logInfo);
        Log::write($logInfo, 'log', true);
    }
}
